//
//  JSExpressQueryController.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/9.
//

import UIKit
import Kingfisher
class name : UIView {
    
}

class searcHeaderView : UIView {
    let margin = 20
    let headerTitle = UILabel()
    let textField = UITextField()
    
    let titleLab = UILabel()
    let telBtn = UIButton()
    let textfield = UITextField()
    let textfield2 = UITextField()
    let switchBtn = UIButton()
    
    let textfield3 = UITextField()
    let codeBtn = UIButton()
    lazy var searchBtn:UIButton = {
        var btn = UIButton()
        btn.setTitle("查  询", for: .normal)
        btn.backgroundColor = .systemBlue
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17.0)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        //    paddingView1.backgroundColor = [UIColor lightGrayColor];
        //    self.phoneTextField .leftView = paddingView1;
        //    self.phoneTextField.leftViewMode = UITextFieldViewModeAlways;
        
        textfield.sg_addLayerBorder(width: 0.5, color: UIColor(r: 22, g: 175, b: 202))
        textfield2.sg_addLayerBorder(width: 0.5, color: UIColor(r: 22, g: 175, b: 202))
        textfield3.sg_addLayerBorder(width: 0.5, color: UIColor(r: 22, g: 175, b: 202))
        textfield.sg_addCorner(radius: 5)
        textfield2.sg_addCorner(radius: 5)
        textfield3.sg_addCorner(radius: 5)
        let space = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))
        let space2 = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))
        let space3 = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))
        textfield.leftView = space
        textfield2.leftView = space2
        textfield3.leftView = space3
        textfield.leftViewMode = .always
        textfield2.leftViewMode = .always
        textfield3.leftViewMode = .always
        
        
//        textfield.sg_addShadow(color: UIColor(r: 48, g: 172, b: 243), offset: CGSize(width: 0, height: 2), radius: 2)
//        textfield2.sg_addShadow(color: UIColor(r: 48, g: 172, b: 243), offset: CGSize(width: 0, height: 2), radius: 2)
//        textfield3.sg_addShadow(color: UIColor(r: 48, g: 172, b: 243), offset: CGSize(width: 0, height: 2), radius: 2)
        titleLab.text = "长通物流单号查询"
        telBtn.setTitle("1234567890", for: .normal)
        telBtn.setTitleColor(.systemBlue, for: .normal)
        
        textfield.placeholder = "请输入单号"
        textfield2.placeholder = "发货人电话"
        textfield3.placeholder = "请输图片验证码"
        
        self.addSubview(titleLab)
        self.addSubview(telBtn)
        self.addSubview(textfield)
        self.addSubview(textfield2)
        self.addSubview(switchBtn)
        self.addSubview(textfield3)
        self.addSubview(codeBtn)
        self.addSubview(searchBtn)
       
        switchBtn.setImage(UIImage(named: "qihuan"), for: .normal)
        

        //        view.showSubviews()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        titleLab.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(10)
            make.height.equalTo(35)
        }
        telBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLab.snp.bottom).offset(10)
            make.height.equalTo(35)
        }
        textfield.snp.makeConstraints { (make) in
            make.left.equalTo(margin)
            make.right.equalTo(-margin)
            make.height.equalTo(35)
            make.top.equalTo(telBtn.snp.bottom).offset(10)
        }
        // 切换收发货人
        switchBtn.snp.makeConstraints { (make) in
            make.top.equalTo(textfield.snp.bottom).offset(10)
            make.right.equalTo(-20)
            make.height.equalTo(35)
            make.width.equalTo(50)
        }
        textfield2.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.top.equalTo(textfield.snp.bottom).offset(10)
            make.right.equalTo(switchBtn.snp.left).offset(-5)
            make.height.equalTo(35)
        }
        // 验证码
        codeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(textfield2.snp.bottom).offset(10)
            make.right.equalTo(-20)
            make.height.equalTo(35)
            make.width.equalTo(70)
        }
        textfield3.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.top.equalTo(textfield2.snp.bottom).offset(10)
            make.right.equalTo(codeBtn.snp.left).offset(-5)
            make.height.equalTo(35)
        }
        searchBtn.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.top.equalTo(textfield3.snp.bottom).offset(20)
            make.right.equalTo(-20)
            make.height.equalTo(35)
            make.bottom.equalTo(self).offset(-10)
        }
    }
}
/// 快递查询及详情
class JSExpressQueryController: UIViewController {
    
    var data:JSListModel = JSListModel()
    
    let margin = 20
    ///数据
    var dataArray:[el] = [el]()
    
    ///    是    string
    var wdid:String = ""
    ///    是    string    手机号
    var mobile:String = ""
    ///    是    string    1发货人，2收货人"
    var type:String = "1"
    ///    是    string    验证码
    var verify:String = ""
    ///    是    string    验证码标识
    var rand:String = ""

    var code : String = ""
    
    ///拉刷新控制器
    var refreshControl = UIRefreshControl()
    
    private lazy var cellId = "cellId"
    

    

    let header = searcHeaderView()
    fileprivate lazy var tableView : UITableView = {
        let tv = UITableView(frame: CGRect.zero, style: .plain)
        tv.register(JSExpViewCell.self, forCellReuseIdentifier: cellId)//注册cell
        tv.translatesAutoresizingMaskIntoConstraints = false// VFL
        //        tv.showsVerticalScrollIndicator = false//垂直滚动指示器
        //        tv.showsHorizontalScrollIndicator = false//水平滚动指示器
        tv.delegate = self
        tv.dataSource = self
        //        tv.bounces = false//弹簧效果
        //        tv.separatorStyle = .none//分割线
        
        // 设置预加载cell高度
        tv.estimatedRowHeight = 55
        // 自动适应cell高度
        tv.rowHeight = UITableView.automaticDimension
        
        
        //        tv.estimatedSectionFooterHeight = 0//预设分区头高度
        //        tv.estimatedSectionHeaderHeight = 0
        tv.backgroundColor = UIColor.white
        if #available(iOS 11.0, *) {
            tv.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        return tv
    }()
    

    var headerTit:String = ""{
        didSet{
            header.headerTitle.text = headerTit
        }
    }
    let noteStr = "物流(快递)单号查询说明:\n1、在查询单号时，请确保您输入的物流(快递)单号是正确的。如无法查询，可通过电话联系物流公司进行查询。\n2、物流(快递)单号包含了您的物流快件的详细信息，通过由数字和字母组成，是您快递包裹的唯一标示代码。物流单号方便物流(快递)公司、发件人以及收件人实时跟踪物流快件的信息。\n3、每家物流和快递公司的单号都有章可循，人们可以从单号中大致判断出是由哪家公司发出的。"
    
    lazy var footer:UIView = {
        var container = UIView()
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.numberOfLines = 0
        lab.textColor = .systemGray2
        lab.text = noteStr
        container.addSubview(lab)
        lab.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.width-40)
        }
       let size = lab.sizeThatFits(CGSize(width: UIScreen.main.bounds.width-40, height: CGFloat(MAXFLOAT)))
        container.frame = CGRect(x: 0, y: 0, width: 414, height: size.height+20)
        return container
    }()
    
    @objc func searchExp(_ btn:UIButton){
        btn.sg_timeInterval(time: 0.5)
        print("searchExp")
        navigationController?.pushViewController(JSExpListController(), animated: true)
    }
    @objc func switchClick(_ btn:UIButton){
        btn.sg_timeInterval(time: 0.3)
        
        btn.isSelected = !btn.isSelected
        if btn.isSelected {
            header.textfield2.placeholder = "发货人电话"
        }else
        {
            header.textfield2.placeholder = "收货人电话"
        }
    }
    @objc func codeClick(_ btn:UIButton){
        btn.sg_timeInterval(time: 0.3)
        btn.setTitle("", for: .normal)
        rand = String.randomStr(length: 6)
        print("urlImage-->",rand)
        let urlImage:ImageResource = ImageResource(downloadURL: URL(string: "http://track.56114.com/index/test/img?id=\(rand)")!)
        btn.imageView!.kf.indicatorType = .activity
        btn.kf.setImage(with: urlImage, for: .normal)
        
    }
    @objc func searchClick(_ btn:UIButton){
        btn.sg_timeInterval(time: 0.3)
        loadData()
    }

    //根据文字获取高度
    func caculateHeight(commemt : String, fontSize : CGFloat, showWidth : CGFloat) -> CGFloat {
        let size:CGSize = CGSize(width:showWidth , height: CGFloat(MAXFLOAT))
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = commemt.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)

        return rect.height
    }
    let disposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.edgesForExtendedLayout = .init()
        header.codeBtn.setTitle("刷新", for: .normal)
        header.codeBtn.setTitleColor(.systemBlue, for: .normal)
        header.codeBtn.addTarget(self, action: #selector(codeClick(_:)), for: .touchUpInside)
        header.searchBtn.addTarget(self, action: #selector(searchClick(_:)), for: .touchUpInside)
        header.switchBtn.addTarget(self, action: #selector(switchClick(_:)), for: .touchUpInside)

//        userVM.username.asObservable().bind(to: textField.rx.text).disposed(by: disposeBag)
        
        
        _ = header.textfield.rx.text.subscribe(onNext: {(text) in
            print(text! as String)
            self.code = (text! as String)
        })
        _ = header.textfield2.rx.text.subscribe(onNext: {(text) in
            print(text! as String)
            self.mobile = (text! as String)
        })
        _ = header.textfield3.rx.text.subscribe(onNext: {(text) in
            print(text! as String)
            self.verify = (text! as String)
        })


        view.addSubview(tableView)
        header.frame = CGRect(x: 0, y: 0, width: 414, height: 300)
        tableView.tableHeaderView = header

        tableView.tableFooterView = footer
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        header.headerTitle.text = "顺丰快递"
        header.textField.text = "124435"
        header.textField.layer.borderWidth = 1.0
        header.textField.layer.cornerRadius = 5.0
        header.textField.layer.masksToBounds = true
        header.textField.layer.borderColor = UIColor.systemBlue.cgColor
        
        let params = ["sid":data.sid]
        HttpRequest.request(.get, getInfo, params) { (result) in
            print(result)

        }
        HttpRequest.GET(getInfo, params) { (result:BaseResponse<JSInfoModel>) in
//            var wdid:String = ""
//            ///    是    string    手机号
//            var mobile:String = ""
//            ///    是    string    1发货人，2收货人"
//            var type:String = "1"
//            ///    是    string    验证码
//            var verify:String = ""
//            ///    是    string    验证码标识
//            var rand:String = ""
//
//            var code : String = ""

            self.wdid = (result.data?.kuaidi?.wdid)!
        }
       
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension JSExpressQueryController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(for: JSExpViewCell.self)

        let model : el = dataArray[indexPath.row]
        cell.timeLab.text = model.time
        cell.content.text = model.content
        
        return cell
    }
    
    
}

extension JSExpressQueryController{
    func loadData() {
//        let params : [String : Any] = [
//            "act":"",            ///    是    string    公司接口类型
//            "name":"",           ///    是    string    公司名称
//            "shortname":"",          ///    是    string    公司简称
//            "companyCode":data!.companyNum, ///    是    string    公司编码
//            "code":"630301195234", ///    是    string    单号
//            "source":"发货宝", ///    是    string    来源 ，例：发货宝
//            "sid":data!.sid, ///    是    string    公司id
//
//            "wdid":"",           ///    是    string
//            "mobile":"67856114",         ///    是    string    手机号
//            "type":"1",           ///    是    string    1发货人，2收货人
//            "verify":"",         ///    是    string    验证码
//            "rand":"",           ///    是    string    验证码标识
//            "zm":"",         ///    是    string    首字母
//        ]
        let params : [String : Any] = [
            "act": "4",
            "wdid": wdid,
            "companyCode": data.companyNum,
            "code": code,
            "source": "发货宝",
            "sid": data.sid,
            "mobile": mobile,
            "type": type,
            "zm": data.zm,
            "verify": verify,
            "rand": rand,
            "name": data.companyName,
            "shortname": data.title
        ]

        HttpRequest.request(.get, searchWL, params) { (result) in
            print(result)
            if let resp = JSONDeserializer<JSSearchModel>.deserializeFrom(json: result.rawString())
            {
                if  let data = resp.data {
                    self.dataArray.append(contentsOf: data)
                    self.tableView.reloadData()
                }else
                {
                    JSShowMessage.showTipMsg("\(resp.msg)", time: 1)
                }
            }
        }
        
    }
}

class scan: NSObject {
    var act:String = "" ///    是    string    公司接口类型
    var name:String = "" ///    是    string    公司名称
    var shortname:String = "" ///    是    string    公司简称
    //    var act:String = "" ///    是    string    公司接口类型
    var companyCode:String = "" ///    是    string    公司编码
    var code:String = "" ///    是    string    单号
    var source:String = "" ///    是    string    来源 ，例：发货宝
    var sid:String = "" ///    是    string    公司id
    var wdid:String = "" ///    是    string
    var mobile:String = "" ///    是    string    手机号
    var type:String = "" ///    是    string    1发货人，2收货人
    var verify:String = "" ///    是    string    验证码
    var rand:String = "" ///    是    string    验证码标识
    var zm:String = "" ///    是    string    首字母
}
